import { pages } from '@/pages'
import { StackActions, createNavigationContainerRef } from '@react-navigation/native'

export const navigationRef = createNavigationContainerRef()

export type TabKey = 'Home' | 'Statistics' | 'Mine'

type PageName = keyof typeof pages | TabKey
type RouteQuery = {
  
}
export default {
  switchTab<N extends TabKey>(name: N, params?: N extends keyof RouteQuery ? RouteQuery[N] : undefined) {
    if (navigationRef.isReady()) {
      ;(navigationRef.navigate as any)('Tab', {
        screen: name,
        params,
      })
    }
  },
  push<N extends PageName>(name: N, params?: N extends keyof RouteQuery ? RouteQuery[N] : undefined) {
    if (navigationRef.isReady()) {
      navigationRef.dispatch(StackActions.push(name, params))
    }
  },
  back(count = 1) {
    if (navigationRef.isReady()) {
      if (navigationRef.canGoBack()) {
        navigationRef.dispatch(StackActions.pop(count))
      } else {
        ;(navigationRef.navigate as any)('Tab', {
          screen: 'Home',
        })
      }
    }
  },
  replace<N extends PageName>(name: N, params?: N extends keyof RouteQuery ? RouteQuery[N] : undefined) {
    if (navigationRef.isReady()) {
      navigationRef.dispatch(StackActions.replace(name, params))
    }
  },
  top() {
    if (navigationRef.isReady()) {
      navigationRef.dispatch(StackActions.popToTop())
    }
  },
  getNavigation() {
    if (navigationRef.isReady()) {
      return navigationRef
    }
  },
}
